import { IResponse } from '@/types/data'
import request from '@/utils/request'
import { defineStore } from 'pinia'
import { IProfile } from '@/types/user'
import { getProfile, removeProfile, setProfile } from '@/utils/storage'
import useStore from '..'

export default defineStore('user', {
  state: () => ({
    // #2 从本地取一下
    profile: getProfile(),
  }),
  actions: {
    // 账号登录
    async login({ account, password }: { account: string; password: string }) {
      const r = await request.post<IResponse<IProfile>>('/login', {
        account,
        password,
      })
      const res = r.data.result
      this.profile = res
      // #1 存一下
      setProfile(res)
    },
    // 发送手机号验证码
    async sendMobileMsg(mobile: string) {
      await request.get('/login/code', {
        params: {
          mobile,
        },
      })
    },
    // 短信登录
    async mobileLogin(mobile: string, code: string) {
      const res = await request.post<IResponse<IProfile>>('/login/code', {
        mobile,
        code,
      })
      const r = res.data.result
      this.profile = r
      // #1 存一下
      setProfile(r)
    },
    logout() {
      this.profile = {} as IProfile
      removeProfile()
      // 清空购物车数据
      useStore().cart.clearCart()
    },
    //  source: 1 为 pc，2 为 webapp，3 为微信小程序, 4 为 Android, 5 为 ios, 6 为 qq, 7 为微信
    async qqLogin(openId: string) {
      const res = await request.post<IResponse<IProfile>>('/login/social', {
        unionId: openId,
        source: 6,
      })
      // 4. 把拿到的结果存储到 Pinia
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 绑定 QQ 的短信验证码
    async sendQQBindMsg(mobile: string) {
      await request.get('/login/social/code', {
        params: {
          mobile,
        },
      })
    },
    // 根据 openid 和手机号（注册过的）及验证码进行绑定
    async qqBindLogin(openId: string, mobile: string, code: string) {
      const res = await request.post<IResponse<IProfile>>('/login/social/bind', {
        mobile,
        code,
        unionId: openId,
      })
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 无账号发送验证码
    async sendQQPathMsg(mobile: string) {
      await request.get('/register/code', {
        params: {
          mobile,
        },
      })
    },
    // 无账号，注册并绑定
    async qqPatchLogin(data: any) {
      const res = await request.post<IResponse<IProfile>>(`/login/social/${data.openId}/complement`, data)
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
    },
  },
})
